package com.webchat.common.util;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class SignUtil {

    /**
     * 签名生成（华为云规范）
     *
     * @param sk
     * @param params
     * @return
     */
    public static String generateSignature(String sk, String ... params) {
        try {
            StringBuffer sign = new StringBuffer();
            if (params != null && params.length > 0) {
                for (int i = 0; i < params.length; i++) {
                    sign.append(params[i]);
                    if (i != params.length - 1) {
                        sign.append("-");
                    }
                }
            }
            Mac sha256HMAC = Mac.getInstance("HmacSHA256");
            SecretKeySpec secretKey = new SecretKeySpec(sk.getBytes(), "HmacSHA256");
            sha256HMAC.init(secretKey);
            byte[] hashBytes = sha256HMAC.doFinal(sign.toString().getBytes(StandardCharsets.UTF_8));
            return Base64.getEncoder().encodeToString(hashBytes);
        } catch (Exception e) {
            throw new RuntimeException("签名生成失败", e);
        }
    }
}